"""
yield生成器入门示例
"""


# 快速入门示例
import sys


# 生成器函数
def countdown(n):
    while n > 0:
        yield n
        n -= 1


# 生成器函数调用
def quick_start_invoke():
    # 创建生成器对象
    generator = countdown(5)
    # 迭代生成器
    print(next(generator))
    print(next(generator))

    for value in generator:
        print(value)
    pass


# 斐波那契数列生成器
def fibonacci_generator(n):
    a, b, counter = 0, 1, 0
    while True:
        if counter > n:
            return
        yield a
        a, b = b, a + b
        counter += 1


class Fibonacci:
    def __init__(self, n):
        self.number = n
        self.a, self.b, self.counter = 0, 1, 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.counter > self.number:
            raise StopIteration
        self.a, self.b = self.b, self.a + self.b
        self.counter += 1
        return self.a


# 斐波那契数列迭代器调用
def fibonacci_iterator_invoke():
    fibonacci = Fibonacci(5)
    iterator = iter(fibonacci)
    for value in iterator:
        print(value)


# 斐波那契数列迭代器调用
def fibonacci_generator_invoke():
    f = fibonacci_generator(10)
    while True:
        try:
            print(next(f), end=" ")
        except StopIteration:
            sys.exit()


def demo_generator():
    x = 1
    yield x + 1
    x += 3
    print(x)


def demo_generator_invoke():
    g = demo_generator()
    print(next(g))
    print(next(g))




# 程序入口
if __name__ == "__main__":
    # quick_start_invoke()
    # fibonacci_generator_invoke()
    # fibonacci_iterator_invoke()
    demo_generator_invoke()
    pass